import { EventEmitter } from "events";
import { readFileSync, watchFile } from "fs";
import { IGlobal } from "./Global";
import { join } from "path";
import { ISqlConfig, IRedisOption, EnumLogLevel } from "./IConfig";
declare var global: IGlobal;
export class Config extends EventEmitter {
    sql: ISqlConfig;
    tokenServer?: string;        //token服务器地址
    port: number;
    redis: IRedisOption;
    logLevels: { [key: string]: EnumLogLevel };
    private _path: string;
    private _env: string;
    private _bMaster: boolean;
    constructor(env: string = "dev", bMaster: string = "false") {
        super();
        this._env = env;
        this._bMaster = bMaster == "true";
        this._path = join(global.rootPath, './config_' + env + '.json');
        watchFile(this._path, this._fileChange.bind(this));
        this._fileChange();
    }

    private _fileChange() {
        let fileContent = readFileSync(this._path).toString();
        try {
            let config = JSON.parse(fileContent);
            for (let key in config) {
                this[key] = config[key];
            }
            global.log && global.log.info("配置文件更新:\n" + fileContent);
            this.emit("change");
        } catch (e) {
            global.log && global.log.error(this._path + "配置文件" + e.message);
        }
    }

    get env() { return this._env; }
    /**是否主要进程 */
    get bMaster() { return this._bMaster; }
}

export var processArg: any = {};
for (let i = 2; i < process.argv.length; i++) {
    let str = process.argv[i];
    str = str.substr(2);
    let arr = str.split("=");
    processArg[arr[0]] = arr[1];
}